package sqlengine.groupby;

import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Vector;

import sqlengine.parser.ParseException;

public class InsertTuple extends Atom{
	private String tableName;
	
	Vector<String> cols = new Vector<String>();
	Vector<String> values = new Vector<String>();	
	
	Map<String, String> tuple = new HashMap<String, String>();
	/**
	 * Default constructor
	 * 
	 * @param tableStr
	 *            the name of the table referenced by this
	 *            <code>INSERT</code>
	 */
	public InsertTuple(){}
	
	public InsertTuple(String tableStr) {
		tableName = tableStr.toLowerCase();		
	}
	/**
	 * Gets the name of the table referenced by this <code>TableDef</code> 
	 * @return the table name
	 */
	public String getTableName() {
		return tableName;
	}
	
	public 	Map<String, String> getTuple() {
		return Collections.unmodifiableMap(tuple);
	}
	
	public void setTableName(String tablename){
		tableName = tablename;
	}
	
	public void addColname(String colname) throws ParseException {		
		cols.add(colname.toLowerCase());		
	} 	
	
	public void addValues(String value) throws ParseException {		
		value = value.substring(1,value.length()-1);		
		int   location;
		while( (location = value.indexOf("\'\'")) >0){ 
			String left = value.substring(0,location); 
			String right = value.substring(location +1,value.length()); 
			value =left+right;
		}
		values.add(value);		
	} 
	
	public void makeTuple(){
		if(cols.size() != values.size() ){
			System.err.println("numbers of column name and values doesn't match");
			throw new IllegalArgumentException();
		}
		//System.err.println("size" + cols.size() + " " + values.size());
		for (int i = 0; i < cols.size(); i++) {
			if(tuple.containsKey(cols.elementAt(i)))
				throw new IllegalArgumentException();
			tuple.put(cols.elementAt(i), values.elementAt(i));
		}
	}

	/**
	 * @see edu.buffalo.db.parser.sqlexpr.Atom#getType()
	 */
	@Override
	public int getType() {
		return Atom.INSERT_ATOM;
	}

	/**
	 * @see java.lang.Object#hashCode()
	 */
	@Override
	public int hashCode() {
		final int PRIME = 31;
		int result = 1;
		result = PRIME * result
				+ ((tableName == null) ? 0 : tableName.hashCode());
		return result;
	}


	
	/**
	 * @see java.lang.Object#toString()
	 */
	@Override
	public String toString() {
		String str = "Table: "+tableName +"\n";
		
		Iterator it = tuple.entrySet().iterator();		
		while (it.hasNext()) {
			Map.Entry pairs = (Map.Entry) it.next();
			str += pairs.getKey() + " " + pairs.getValue() + "\n";
		}
		return str;
	}
}
